import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo02 {
    private static final ReentrantLock Lock = new ReentrantLock();
    private static final Condition CONDITION = Lock.newCondition();

    public static final int end = 100;
    public static volatile int start = 0; // 起始值改为1，因为要打印1-100

    public static final int THREAD_NUM = 3;

    public static class Print implements Runnable {
        public int index;

        public Print(int index) {
            this.index = index;
        }

        @Override
        public void run() {
            while (start < end) {
                Lock.lock();
                try {
                    //START和线程数进行取余，如果不等于当前线程的则等待
                    while (start % THREAD_NUM != index) {
                        try {
                            CONDITION.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //否则进行输出
                    if (start <= end) {
                        System.out.println("Thread" + (index + 1) + ",打印结果：" + start);
                    }
                    start++;
                    //唤醒等待线程
                    CONDITION.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Lock.unlock();
                }

            }

        }

        public static void main(String[] args) {
            for (int i = 0; i <= THREAD_NUM; i++) {
                new Thread(new Demo02.Print(i)).start();
            }
        }
    }
}

